
'use strict';

var gulp     = require('gulp');
var fs       = require('fs');
var path     = require('path');
var sass     = require('gulp-sass');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var gutil    = require('gulp-util');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var replace   = require('gulp-replace');
var uglify   = require('uglify-js');


// projects directories and pathes
var dir = {
    sass: './css/_scss',
    css: './css',
    img: './images'
}, paths = {
    sass: dir.sass + '/**/*.scss',
    img: dir.img + '/**/*.*',
    css: dir.css + '/*.css'
}, output = {
    root: './',
    templates: './templates',
    img: './images'
};

function onError (err){

    gutil.beep()
    console.log( err );
}

var staticRootPath = '//static.zhongan.com/website/other/html/smashegg';

/* ============
 * Task: compile .scss file
 * ============
 **/

gulp.task('sass', function () {
  gulp.src(paths.sass)
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(gulp.dest(dir.css));
});

/* ============
 * Task: watch .scss file
 * ============
 **/
gulp.task( 'watch:sass', function () {
    return gulp.watch( paths.sass, ['sass'] );
});

gulp.task( 'build:img', function(){

    return gulp.src( paths.img )
       .pipe(imagemin({
            progressive: false,
            optimizationLevel:7,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
       .pipe(gulp.dest(output.img));
});

gulp.task( 'copy', function(){

    gulp.src('./images/**/*.*')
        .pipe(gulp.dest('./build/images'));

    gulp.src('./res/**/*.*')
        .pipe(gulp.dest('./build/res'));
})

gulp.task( 'build', ['copy'], function(){

    var css = /<link\s+rel="stylesheet"\s+href="([^"]+)"\s*\/>/ig;
    var js = /<script\s+src="([^"]+)"><\/script>/ig;
    var src = /src="([^"]+)"/ig;

    return gulp.src('./index.html')
    .pipe(replace(css, function( target, p0 ){

        var fileCnt = fs.readFileSync(path.join( './', p0), 'utf-8').toString();
        if(fileCnt){
            fileCnt = fileCnt.replace(/..\/images\//g, staticRootPath + 'images/' );
        }

        return '<style type="text/css">\n' + fileCnt + '\n</style>'
    }))
    .pipe(replace(js, function( target, p0 ){

        var filePath = path.join( './', p0),
            fileCnt = '';

        if(p0.indexOf('.min.js')==-1){
            fileCnt = uglify.minify(p0).code.toString();
        }
        else{
            fileCnt = fs.readFileSync(filePath).toString();
        }

        return '<script>\n' + fileCnt + '\n</script>'
    }))
    .pipe(replace(src, function(target, p0){

        if(/^(http:|https:|\$)?\/\//.test(p0) || /^data:/.test(p0)){

            return target;
        }

        return 'src="' + staticRootPath + p0 + '"';
    }))
    .pipe(gulp.dest('./build'));
})

gulp.task( 'server', function(){

    browserSync({
        server: true,
        startPath:'index.html',
        notify: false
    }, function(err, bs) {
        console.log(bs.options.getIn(["urls", "local"]));
    });

    var reload = browserSync.reload;
    gulp.watch(["./**/*.js", "./**/*.html", "./css/*.css"]).on('change', reload);
})

gulp.task( 'default', ['server', 'watch:sass' ]);
